package com.wty.aop;

import com.wty.annotation.RoutingDataSource;
import com.wty.common.DataSourceContextHolder;
import com.wty.common.DataSources;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @Author wangtengyu
 * @Create 2018-08-30-19:50
 */
@Aspect
@Component
@Slf4j
public class MyAspect {


    @Before("@annotation(com.wty.annotation.RoutingDataSource)")
    public void before(JoinPoint joinPoint) {
        //获取class
        Class className = joinPoint.getTarget().getClass();
        //获取方法名
        String methodName = joinPoint.getSignature().getName();
        Class[] argClass = ((MethodSignature) joinPoint.getSignature()).getParameterTypes();

        String dataSource = DataSources.DEFAULT_DATASOURCE;

        try {
            Method method = className.getMethod(methodName, argClass);
            if (method.isAnnotationPresent(RoutingDataSource.class)) {
                RoutingDataSource annotation = method.getAnnotation(RoutingDataSource.class);
                dataSource = annotation.value();
            }
        } catch (NoSuchMethodException e) {
            log.error("routing datasource exception, " + methodName, e);
        }
        DataSourceContextHolder.setDB(dataSource);

    }

    @After("@annotation(com.wty.annotation.RoutingDataSource)")
    public void afterSwitchDS(JoinPoint point) {
        DataSourceContextHolder.clearDB();
    }

}
